<template>
  <div class="container">
    <!-- from表单 -->
    <el-form
      :model="addTagsFrom"
      :rules="addTagsFromRules"
      ref="addTagsFromRef"
      label-width="100px"
      class="demo-addTagsFrom"
    >
      <!-- 所属学科 -->
      <el-form-item label="所属学科" v-if="status">
        <el-select v-model="addTagsFrom.subjectID" placeholder="请选择">
          <template>
            <el-option
              v-for="(item, index) in subjectList"
              :key="index"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </template>
        </el-select>
      </el-form-item>
      <!-- 目录名称 -->
      <el-form-item label="目录名称" prop="tagName">
        <el-input v-model="addTagsFrom.tagName"></el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button @click="$emit('close', addTagsFrom)">取 消</el-button>
        <el-button type="primary" @click="addTags">确 定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { simple } from "../../api/hmmm/subjects";
import { add } from "@/api/hmmm/tags";
export default {
  name: "AddTags",
  components: {},
  props: {
    status: {
      type: Boolean,
      required: false,
      default: true
    },
    subjectId: {
      type: [Number, String],
      required: false,
      default: ""
    }
  },
  data() {
    return {
      addTagsFrom: {
        tagName: "",
        subjectID: null
      },
      // 所有学科列表的数据
      subjectList: {},
      // 添加标签表单的校验方法
      addTagsFromRules: {
        tagName: [
          { required: true, message: "请输入目录名称", trigger: "blur" }
        ]
      }
    };
  },
  computed: {},
  watch: {},
  created() {
    // 获取所有学科列表
    this.getSubjectList();
    if (this.subjectId) {
      this.addTagsFrom.subjectID = Number(this.subjectId);
    }
    console.log(this.subjectId);
  },
  mounted() {},
  methods: {
    // 获取所有的学科列表
    async getSubjectList() {
      const { data } = await simple();
      console.log(data);
      this.subjectList = data;
    },
    // 点击确定添加
    addTags() {
      // 表单预校验
      this.$refs.addTagsFromRef.validate(async valid => {
        if (valid) {
          try {
            // 表单校验通过发送数据请求添加
            console.log(this.addTagsFrom);
            await add(this.addTagsFrom);
            // 关闭对话框
            this.$emit("close", this.addTagsFrom);
            // 重新获取数据
            this.$emit("success");
            this.$message.success("添加成功！");
          } catch (error) {
            this.$message.error("添加失败，请稍后重试");
          }
        } else {
          this.$message.error("请填写必填参数");
        }
      });
    }
  }
};
</script>

<style scoped lang="less">
.el-select {
  width: 100%;
}
.btns {
  display: flex;
  justify-content: flex-end;
}
</style>
